<template>
  <view class="container">
    <!-- 宠物头像和基本信息 -->
    <view class="pet-header-card" v-if="pet">
      <view class="avatar-section">
        <image :src="pet.photo || '/static/img/default-pet.png'" class="pet-avatar" mode="aspectFill"></image>
      </view>
      <view class="pet-info-section">
        <view class="pet-details">
          <view class="pet-detail-item">
            <image src="/static/pet/姓名.png" class="detail-icon"></image>
            <text class="detail-text">{{ pet.name }}</text>
          </view>
          <view class="pet-detail-item" v-if="pet.breed">
            <image src="/static/pet/品种名称.png" class="detail-icon"></image>
            <text class="detail-text">{{ pet.breed }}</text>
          </view>
          <view class="pet-detail-item" v-if="pet.gender">
            <image src="/static/pet/性别.png" class="detail-icon"></image>
            <text class="detail-text gender">{{ pet.gender }}</text>
          </view>
          <view class="pet-detail-item" v-if="pet.birthday">
            <image src="/static/pet/生日.png" class="detail-icon"></image>
            <text class="detail-text">{{ formatDate(pet.birthday) }}</text>
          </view>
          <view class="pet-detail-item" v-if="pet.type">
            <image src="/static/pet/类型.png" class="detail-icon"></image>
            <text class="detail-text">{{ pet.type }}</text>
          </view>
          <view class="pet-detail-item" v-if="pet.weight">
            <image src="/static/pet/体重.png" class="detail-icon"></image>
            <text class="detail-text">{{ pet.weight }} kg</text>
          </view>
          <view class="pet-detail-item" v-if="pet.color">
            <image src="/static/pet/颜色.png" class="detail-icon"></image>
            <text class="detail-text">{{ pet.color }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 操作按钮 -->
    <view class="action-buttons">
      <button class="action-btn health-btn" @click="goToAddHealthRecord">
        <text class="btn-icon">+</text> 增加健康记录
      </button>
      <button class="action-btn edit-btn" @click="goToEditPet">
        <text class="btn-icon">✏️</text> 编辑宠物
      </button>
    </view>

    <!-- 健康记录Tab -->
    <view class="section-card">
      <view class="section-title">健康记录</view>
      <view class="tab-container">
        <view 
          v-for="(tab, index) in healthTabs" 
          :key="index"
          class="tab-item"
          :class="{ active: currentTab === index }"
          @click="switchTab(index)"
        >
          {{ tab.dictLabel || tab }}
        </view>
      </view>
      
      <view class="tab-content">
        <view v-if="filteredHealthRecords.length > 0">
          <view class="health-item" v-for="record in filteredHealthRecords" :key="record.id">
                 <view class="health-content" @click="goToEditHealthRecord(record)">
                   <view class="health-title">{{ record.title || record.content || '无标题' }}</view>
                   <view class="health-date">日期: {{ formatDateTime(record.recordDate || record.recordDate) }}</view>
                   
                  </view>
                 <view class="health-actions">
                   <button v-if="record.reminderId" class="action-btn reminder-btn-small" @click.stop="viewReminder(record)">
                     <text class="btn-icon-text">🔔</text> 查看提醒
                   </button>
                   <button v-else class="action-btn reminder-btn-small" @click.stop="addReminder(record)">
                     <text class="btn-icon-text">➕</text> 添加提醒
                   </button>
                   <button class="action-btn delete-btn-small" @click.stop="showDeleteMenu(record)">
                     <image src="/static/img/delete.png" class="btn-icon-img"></image> 删除
                   </button>
                 </view>
          </view>
        </view>
        <view v-else class="empty-text">暂无{{ (healthTabs[currentTab] && healthTabs[currentTab].dictLabel) || healthTabs[currentTab] }}记录</view>
      </view>
    </view>

    <!-- 定位历史 -->
    <view class="section-card">
      <view class="section-title">定位历史</view>
      <view v-if="locationRecords.length > 0">
        <view class="location-item" v-for="loc in locationRecords" :key="loc.id">
          <view>时间: {{ formatDateTime(loc.locationTime) }}</view>
          <view>经度: {{ loc.longitude }} 纬度: {{ loc.latitude }}</view>
          <view v-if="loc.address">地址: {{ loc.address }}</view>
        </view>
      </view>
      <view v-else class="empty-text">暂无定位记录</view>
    </view>

    <!-- 底部弹出删除菜单 -->
    <view class="action-sheet" v-if="showActionSheet" @click="hideActionSheet">
      <view class="action-sheet-content" @click.stop>
        <view class="action-sheet-header">
          <text class="action-sheet-title">操作</text>
          <text class="action-sheet-cancel" @click="hideActionSheet">取消</text>
        </view>
        <view class="action-sheet-options">
          <view class="action-sheet-option delete-option" @click="deleteHealthRecord">
            <text class="option-text">删除记录</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { getPetDetail, deletePet } from '@/api/pet.js'
import { getHealthList, deleteHealthRecord, updateHealthRecord } from '@/api/health.js'
import { checkAndRedirectToLogin } from '@/utils/auth'
import { getDictData } from '@/api/dict.js'

export default {
  data() {
    return {
      pet: null,
      healthRecords: [],
      locationRecords: [],
      loading: false,
      currentTab: 0,
      healthTabs: [],
      showActionSheet: false,
      selectedRecord: null
    }
  },
  onLoad(options) {
    const petId = options.id
    if (petId) {
      this.petId = petId
      this.loadPetDetail()
      this.loadHealthRecords(petId)
      this.loadLocationRecords(petId)
      this.loadDictData()
    }
  },
  onShow() {
    // 监听健康记录更新事件
    uni.$on('healthrecordupdated', () => {
  
      if (this.petId) {
        this.loadHealthRecords(this.petId)
      }
    })
    
    // 每次页面显示时都刷新健康记录数据
    if (this.petId) {
      this.loadHealthRecords(this.petId)
    }
  },
  onUnload() {
    // 页面卸载时移除事件监听，避免内存泄漏
    uni.$off('healthrecordupdated')
  },
  computed: {
    filteredHealthRecords() {
      const currentTabType = (this.healthTabs[this.currentTab] && this.healthTabs[this.currentTab].dictLabel) || this.healthTabs[this.currentTab]
      return this.healthRecords.filter(record => {
        const recordType = record.type || record.recordType
        return recordType === currentTabType
      })
    },
    

  },
  methods: {
    async loadPetDetail() {
      try {
      this.loading = true
        uni.showLoading({ title: '加载中...' })

        const response = await getPetDetail(this.petId)
        
        if (response && response.code === 200) {
          this.pet = response.data
  
        } else {
          uni.showToast({ title: response?.msg || '加载失败', icon: 'none' })
          setTimeout(() => uni.navigateBack(), 1500)
        }
      } catch (error) {
    
        uni.showToast({ title: '网络错误', icon: 'none' })
        setTimeout(() => uni.navigateBack(), 1500)
      } finally {
        this.loading = false
        uni.hideLoading()
      }
    },
    async loadHealthRecords(petId) {
      try {
    
        // 使用统一的认证检查函数
        if (!checkAndRedirectToLogin('请先登录')) {
          return
        }
        
        // 使用getHealthList方法，通过petId参数筛选特定宠物的健康记录
        const response = await getHealthList({ petId: petId })
    
        
        if (response && response.code === 200) {
          // 直接使用返回的健康记录数据
          const healthData = response.data || response.rows || []
      
      
          
          // 使用Vue.set或直接赋值确保响应式更新
          this.healthRecords = Array.isArray(healthData) ? [...healthData] : []
          
      
      
      
          
          
          // 强制触发Vue响应式更新
          this.$forceUpdate()
        } else {
    
          this.healthRecords = []
        }
      } catch (error) {
  
        this.healthRecords = []
      }
    },
    
    async loadLocationRecords(petId) {
      try {
        
        // 使用统一的认证检查函数
        if (!checkAndRedirectToLogin('请先登录')) {
          return
        }
        
        // 暂时使用模拟数据，因为位置记录API可能还未实现
        // TODO: 实现实际的位置记录API调用

        
        // 模拟位置记录数据
        this.locationRecords = [
          {
            id: 1,
            locationTime: new Date().toISOString(),
            longitude: '116.397128',
            latitude: '39.916527',
            address: '北京市东城区王府井大街'
          }
        ]
      } catch (error) {
    
        this.locationRecords = []
      }
    },

    async deletePet() {
      try {
        const result = await uni.showModal({
          title: '确认删除',
          content: '确定要删除这个宠物吗？删除后将同时删除所有相关健康记录，且无法恢复。',
          confirmText: '删除',
          confirmColor: '#ff4444'
        })

        if (result.confirm) {
          uni.showLoading({ title: '删除中...' })
          
          // 1. 先获取该宠物的所有健康记录
          const healthResponse = await getHealthList({ petId: this.petId })
          let healthRecords = []
          if (healthResponse && healthResponse.code === 200) {
            healthRecords = healthResponse.data || healthResponse.rows || []
          }
          
          // 2. 删除所有健康记录
          if (healthRecords.length > 0) {
            const deletePromises = healthRecords.map(record => 
              deleteHealthRecord(record.id).catch(err => {
          
                // 单个健康记录删除失败不影响整体流程
                return null
              })
            )
            await Promise.all(deletePromises)
          }
          
          // 3. 删除宠物
          const response = await deletePet(this.petId)
          
          if (response && response.code === 200) {
            uni.showToast({ title: '删除成功', icon: 'success' })
            setTimeout(() => uni.navigateBack(), 1500)
          } else {
            uni.showToast({ title: response?.msg || '删除失败', icon: 'none' })
          }
        }
      } catch (error) {
  
        uni.showToast({ title: '网络错误', icon: 'none' })
      } finally {
        uni.hideLoading()
      }
    },
    goBack() {
      uni.navigateBack()
    },
    
    switchTab(index) {
      this.currentTab = index
    },
    
    goToAddHealthRecord() {
      uni.navigateTo({
        url: `/pages/health/add?petId=${this.petId}&petName=${encodeURIComponent(this.pet.name)}`
      })
    },
    
    goToEditPet() {
      uni.navigateTo({
        url: `/pages/pet/edit?id=${this.petId}`
      })
    },
    
    goToEditHealthRecord(record) {
      uni.navigateTo({
        url: `/pages/health/edit?id=${record.id}&petId=${this.petId}&petName=${encodeURIComponent(this.pet.name)}`
      })
    },

    showDeleteMenu(record) {



      this.selectedRecord = record
      this.showActionSheet = true
    },



    hideActionSheet() {
      this.showActionSheet = false
      this.selectedRecord = null
    },
    


    async deleteHealthRecord() {
      if (!this.selectedRecord) {
  
        return
      }
      


      
      try {
        // 使用Promise包装uni.showModal以确保正确处理回调
        const result = await new Promise((resolve, reject) => {
          uni.showModal({
            title: '确认删除',
            content: '确定要删除这条健康记录吗？删除后无法恢复。',
            confirmText: '删除',
            confirmColor: '#ff4444',
            success: (res) => {
        
              resolve(res)
            },
            fail: (err) => {
      
              reject(err)
            }
          })
        })

  
        
        if (result.confirm) {
  
          uni.showLoading({ title: '删除中...' })
          
          const response = await deleteHealthRecord(this.selectedRecord.id)
    
          
          if (response && response.code === 200) {
      
            uni.showToast({ title: '删除成功', icon: 'success' })
            // 重新加载健康记录
            this.loadHealthRecords(this.petId)
          } else {
      
            uni.showToast({ title: response?.msg || '删除失败', icon: 'none' })
          }
        } else {
    
        }
      } catch (error) {
  
        uni.showToast({ title: '网络错误', icon: 'none' })
      } finally {
        this.hideActionSheet()
        uni.hideLoading()
      }
    },
    
    formatStatus(status) {
      // 将状态值转换为中文显示
      if (status === '0' || status === 0 || status === 'pending') {
        return '待处理'
      } else if (status === '1' || status === 1 || status === 'completed') {
        return '已完成'
      }
      return status || '未知'
    },
    formatDate(dateStr) {
      if (!dateStr) return ''
      const date = new Date(dateStr)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
    },
    formatDateTime(dateTime) {
      if (!dateTime) return ''
      const date = new Date(dateTime)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
    },
  
  async loadDictData() {
    try {
      // 加载健康记录类型字典
      const healthTypeResponse = await getDictData('pet_health_type')
      if (healthTypeResponse && healthTypeResponse.code === 200) {
        // 新的api返回格式包含分页信息，需要从rows或list中提取数据
        this.healthTabs = healthTypeResponse.data.rows || healthTypeResponse.data.list || healthTypeResponse.data || []
      } else {
        // 默认值
        this.healthTabs = [
          { dictLabel: '疫苗', dictValue: 'vaccine' },
          { dictLabel: '驱虫', dictValue: 'deworming' },
          { dictLabel: '体检', dictValue: 'checkup' },
          { dictLabel: '其他', dictValue: 'other' }
        ]
      }
    } catch (error) {

      // 使用默认值
      this.healthTabs = [
        { dictLabel: '疫苗', dictValue: 'vaccine' },
        { dictLabel: '驱虫', dictValue: 'deworming' },
        { dictLabel: '体检', dictValue: 'checkup' },
        { dictLabel: '其他', dictValue: 'other' }
      ]
    }
  },
  
  // 查看提醒
  viewReminder(record) {
    if (record.reminderId) {
      // 跳转到提醒详情页面查看提醒
      uni.navigateTo({
        url: `/pages/calendar/edit?reminderId=${record.reminderId}&healthRecordId=${record.id}`
      })
    } else {
      uni.showToast({
        title: '该记录没有关联的提醒',
        icon: 'none'
      })
    }
  },
  
  // 添加提醒
  addReminder(record) {
    // 跳转到日历添加页面，传递健康记录信息和宠物信息
    uni.navigateTo({
      url: `/pages/calendar/add?healthRecordId=${record.id}&type=${record.type || record.recordType}&title=${encodeURIComponent(record.title || record.content || '健康记录')}&petId=${this.petId}&petName=${encodeURIComponent(this.pet.name)}`
    })
  }
}
}
</script>

<style scoped>
.container {
  padding: 20rpx;
  background: #f5f5f5;
  min-height: 100vh;
}
.nav-bar {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}
.back-btn {
  background: #007AFF;
  color: #fff;
  border: none;
  border-radius: 8rpx;
  padding: 10rpx 30rpx;
  margin-right: 20rpx;
}
.title {
  font-size: 32rpx;
  font-weight: bold;
}
.pet-header-card {
  background: #fff;
  border-radius: 15rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.08);
  text-align: center;
}
.avatar-section {
  margin-bottom: 20rpx;
}
.pet-avatar {
  width: 160rpx;
  height: 160rpx;
  border-radius: 50%;
  margin: 0 auto;
  display: block;
}
.pet-info-section {
  text-align: center;
}
.pet-name {
  font-size: 40rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
}
.gender {
  color: #007AFF;
}
.pet-details {
  display: flex;
  flex-direction: column;
  gap: 15rpx;
}
.pet-detail-item {
    display: flex;
    align-items: center;
    font-size: 32rpx;
    color: #333;
    padding: 12rpx 0 12rpx 20rpx;
    gap: 40rpx;
  }
.detail-icon {
  width: 36rpx;
  height: 36rpx;
}
.detail-text {
  line-height: 32rpx;
}
.section-card {
  background: #fff;
  border-radius: 15rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.06);
}
.section-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #007AFF;
  margin-bottom: 20rpx;
}

/* 操作按钮样式 */
.action-buttons {
  display: flex;
  gap: 20rpx;
  margin-bottom: 30rpx;
  padding: 0 20rpx;
}
.action-btn {
  flex: 1;
  height: 80rpx;
  border-radius: 40rpx;
  border: none;
  font-size: 28rpx;
  font-weight: bold;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10rpx;
}
.health-btn {
  background: #007AFF;
  color: #fff;
}
.edit-btn {
  background: #4CD964;
  color: #fff;
}
.btn-icon {
  font-size: 32rpx;
}

/* Tab样式 */
.tab-container {
  display: flex;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 20rpx;
}
.tab-item {
  flex: 1;
  text-align: center;
  padding: 20rpx 0;
  font-size: 28rpx;
  color: #666;
  border-bottom: 3rpx solid transparent;
  transition: all 0.3s ease;
}
.tab-item.active {
  color: #007AFF;
  border-bottom-color: #007AFF;
  font-weight: bold;
}
.tab-content {
  min-height: 200rpx;
}
.health-item, .location-item {
  border-bottom: 1px solid #f0f0f0;
  padding: 16rpx 0;
  user-select: none;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  cursor: pointer;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.health-content {
  flex: 1;
  padding-right: 20rpx;
}

.health-content:active {
  background-color: #f9f9f9;
}

.health-actions {
  display: flex;
  gap: 8rpx;
  flex-shrink: 0;
  height: 100%;
  align-items: center;
  white-space: nowrap;
}

.edit-btn-small, .delete-btn-small, .complete-btn-small, .regenerate-btn-small, .reminder-btn-small {
  padding: 6rpx 12rpx;
  border-radius: 20rpx;
  border: none;
  font-size: 22rpx;
  display: flex;
  align-items: center;
  gap: 4rpx;
  min-width: auto;
  width: auto;
  justify-content: center;
  background: transparent;
  color: #333;
  white-space: nowrap;
}

.complete-btn-small {
  color: #4CD964;
}

.regenerate-btn-small {
  color: #007AFF;
}

.reminder-btn-small {
  color: #FF9500;
}

.btn-icon-text {
  font-size: 24rpx;
  font-weight: bold;
}

.btn-icon-img {
  width: 24rpx;
  height: 24rpx;
}
.health-title {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
}
.health-type, .health-date, .health-status {
  font-size: 24rpx;
  color: #666;
  margin-right: 20rpx;
}
.empty-text {
  color: #bbb;
  text-align: center;
  font-size: 26rpx;
  padding: 30rpx 0;
}

/* 底部弹出菜单样式 */
.action-sheet {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 999;
  display: flex;
  align-items: flex-end;
}

.action-sheet-content {
  width: 100%;
  background: #fff;
  border-radius: 20rpx 20rpx 0 0;
  overflow: hidden;
}

.action-sheet-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1px solid #f0f0f0;
}

.action-sheet-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.action-sheet-cancel {
  font-size: 28rpx;
  color: #666;
}

.action-sheet-options {
  padding: 20rpx 0;
}

.action-sheet-option {
  padding: 30rpx;
  text-align: center;
  font-size: 28rpx;
  color: #333;
  border-bottom: 1px solid #f0f0f0;
}

.action-sheet-option:last-child {
  border-bottom: none;
}

.delete-option {
  color: #ff4444;
}

.option-text {
  font-weight: bold;
}
</style>